<template>
  <div>
    <h1>商品列表</h1>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.prodName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input
            v-model="searchForm.prodId"
            placeholder="请输入"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
          <el-button type="primary" @click="addProdSubmit">添加商品</el-button>
          <el-button type="danger" @click="onDeleteBatchProd"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="编号" width="80px" />
        <el-table-column prop="prodSpu" label="SPU" width="100px" />
        <el-table-column prop="prodName" label="商品名称" width="100px" />
        <el-table-column prop="typeName" label="商品分类" width="100px" />
        <el-table-column prop="brandName" label="商品品牌" width="100px" />
        <el-table-column prop="unitName" label="商品单位" width="100px" />
        <el-table-column prop="tagName" label="商品标签" width="100px" />
        <el-table-column prop="prodStatus" label="状态" width="100px">
          <template #default="scope">
            <span v-if="scope.row.prodStatus == 0">下架</span>
            <span v-if="scope.row.prodStatus == 1">上架</span>
          </template>
        </el-table-column>
        <el-table-column prop="prodKind" label="商品类型" width="100px">
          <template #default="scope">
            <span v-if="scope.row.prodKind == 0">实物商品</span>
            <span v-if="scope.row.prodKind == 1">虚拟商品</span>
            <span v-if="scope.row.prodKind == 2">卡密/网盘</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="120px" />
        <el-table-column prop="prodImage" label="商品缩略图" width="120px">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-image
                :src="scope.row.prodImage"
                style="width: 50px; height: 50px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleProdInfo(scope.row)"
            >
              商品明细
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="onAddAtta(scope.row)"
            >
              商品附件
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div>
        <el-dialog v-model="dialogFormVisible" title="添加商品" width="500">
          <el-form :model="form" ref="ruleFormRef" :rules="rules">
            <el-form-item
              label="商品SPU"
              :label-width="formLabelWidth"
              prop="prodSpu"
            >
              <el-input v-model="form.prodSpu" autocomplete="off" />
            </el-form-item>
            <el-form-item
              label="商品名称"
              :label-width="formLabelWidth"
              prop="prodName"
            >
              <el-input v-model="form.prodName" autocomplete="off" />
            </el-form-item>
            <el-form-item
              label="商品分类"
              :label-width="formLabelWidth"
              prop="prodType"
            >
              <el-tree-select
                v-model="form.prodType"
                :data="typeList"
                :render-after-expand="false"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item
              label="商品品牌"
              :label-width="formLabelWidth"
              prop="brandId"
            >
              <el-select v-model="form.brandId" placeholder="请选择品牌">
                <el-option
                  v-for="item in brandList"
                  :label="item.brandName"
                  :value="item.brandId"
                  :key="item.brandId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="商品单位"
              :label-width="formLabelWidth"
              prop="unitId"
            >
              <el-select v-model="form.unitId" placeholder="请选择单位">
                <el-option
                  v-for="item in unitList"
                  :label="item.dictName"
                  :value="item.dictId"
                  :key="item.dictId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="商品标签"
              :label-width="formLabelWidth"
              prop="tagId"
            >
              <el-select v-model="form.tagId" placeholder="请选择商品标签">
                <el-option
                  v-for="item in tagList"
                  :label="item.tagName"
                  :value="item.tagId"
                  :key="item.tagId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="供应商"
              :label-width="formLabelWidth"
              prop="appr"
            >
              <el-input v-model="form.appr" autocomplete="off" />
            </el-form-item>
            <el-form-item
              label="商品状态"
              :label-width="formLabelWidth"
              prop="prodStatus"
            >
              <el-radio-group v-model="form.prodStatus">
                <el-radio value="0">上架</el-radio>
                <el-radio value="1">下架</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="商品类型"
              :label-width="formLabelWidth"
              prop="prodKind"
            >
              <el-radio-group v-model="form.prodKind">
                <el-radio value="0">实物商品</el-radio>
                <el-radio value="1">虚拟商品</el-radio>
                <el-radio value="2">卡密/网盘</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="商品缩略图"
              :label-width="formLabelWidth"
              prop="prodImage"
            >
              <el-upload
                class="avatar-uploader"
                action="http://localhost:10010/prod/type/uploadImages"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>

        <el-dialog
          v-model="dialogFormVisibless"
          title="商品附件添加"
          width="500"
        >
          <el-form :model="form">
            <el-form-item label="商品轮播图" :label-width="formLabelWidth">
              <el-upload
                v-model:file-list="fileList"
                action="http://localhost:10010/prod/type/uploadImages"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
            <el-form-item label="商品视频" :label-width="formLabelWidth">
              <el-upload
                v-model:file-list="videoList"
                class="upload-demo"
                action="http://localhost:10010/prod/type/uploadImages"
                multiple
                :on-preview="handlePreview"
                :on-remove="handleVideoRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-button type="primary">上传视频</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    作用于商品详情页顶部轮插的视频介绍，最大限制20MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="上架时间" :label-width="formLabelWidth">
              <el-radio-group v-model="formAtta.upFlag">
                <el-radio value="0">立即上架</el-radio>
                <el-radio value="1">定时上架</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label=""
              :label-width="formLabelWidth"
              v-if="formAtta.upFlag == 1"
            >
              <el-date-picker
                v-model="formAtta.upTime"
                type="datetime"
                placeholder="请选择定时上架时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="定时下架" :label-width="formLabelWidth">
              <el-switch
                v-model="formAtta.downFlag"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            <el-form-item
              label=""
              :label-width="formLabelWidth"
              v-if="formAtta.downFlag == 1"
            >
              <el-date-picker
                v-model="formAtta.downTime"
                type="datetime"
                placeholder="请选择下架时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="onSubmitProdAtta">
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { ComponentSize, UploadUserFile } from "element-plus";
import {
  getProdList,
  getTag,
  getDictList,
  getSelectTypeTree,
  getBrandList,
  addProdList,
  deleteBatchProd,
  addProdAtta,
} from "../api/api";
import type { FormInstance, FormRules } from "element-plus";

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleVideoRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

const tableData = ref([]);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
  prodId: "",
  prodName: null,
});
const total = ref(0);

import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps } from "element-plus";
import router from "@/router";

const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};
const formAtta = ref({
  attaId: 0,
  attaImages: null,
  attaVideo: null,
  downFlag: null,
  downTime: null,
  prodId: null,
  upFlag: null,
  upTime: null,
});
interface RuleForm {
  appr: string;
  brandId: string;
  prodImage: string;
  prodKind: string;
  prodName: string;
  prodSpu: string;
  prodStatus: string;
  prodType: string;
  tagId: string;
  unitId: string;
}

const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};
const loadList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
const dialogFormVisible = ref(false);
const dialogFormVisibless = ref(false);

const formLabelWidth = "140px";

const form = ref({
  appr: "",
  brandId: "",
  brandName: "",
  createBy: "",
  createTime: "",
  prodId: "",
  prodImage: "",
  prodKind: "",
  prodName: "",
  prodSpu: "",
  prodStatus: "",
  prodType: "",
  tagId: "",
  tagName: "",
  typeName: "",
  unitId: "",
  unitName: "",
  uodateBy: "",
  updateTime: "",
});
interface RuleForm {
  appr: string;
  brandId: string;
  prodImage: string;
  prodKind: string;
  prodName: string;
  prodSpu: string;
  prodStatus: string;
  prodType: string;
  tagId: string;
  unitId: string;
}

const ruleFormRef = ref<FormInstance>();

const rules = ref<FormRules<RuleForm>>({
  appr: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
  brandId: [{ required: true, message: "商品品牌不能为空", trigger: "blur" }],
  prodKind: [{ required: true, message: "商品类型不能为空", trigger: "blur" }],
  prodName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  prodSpu: [{ required: true, message: "商品SPU不能为空", trigger: "blur" }],
  prodStatus: [
    { required: true, message: "商品状态不能为空", trigger: "blur" },
  ],
  prodType: [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
  tagId: [{ required: true, message: "商品标签不能为空", trigger: "blur" }],
  unitId: [{ required: true, message: "商品单位不能为空", trigger: "blur" }],
});

const typeList = ref([]);
const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);

const addProdSubmit = () => {
  dialogFormVisible.value = true;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.value.prodImage = imageUrl.value;
      addProdList(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const multipleSelection = ref<any[]>([]);

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log("handleSelectionChange", multipleSelection.value);
};

//商品批量删除
const onDeleteBatchProd = () => {
  let ids = [];

  //参数检查
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除取得商品");
    return;
  }

  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });

  ElMessageBox.confirm("删除后无法恢复，确认删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //确认删除
      deleteBatchProd(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      //取消删除
    });
};
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const fileList = ref<UploadUserFile[]>([]);
const videoList = ref<UploadUserFile[]>([]);

const onAddAtta = (row: any) => {
  //清空轮播图
  fileList.value = [];

  //清空视频
  videoList.value = [];

  formAtta.value = {
    attaId: 0,
    attaImages: null,
    attaVideo: null,
    downFlag: null,
    downTime: null,
    prodId: null,
    upFlag: null,
    upTime: null,
  };

  dialogFormVisibless.value = true;
  formAtta.value.prodId = row.prodId;
  console.log(row);
};

//提交添加商品附件
const onSubmitProdAtta = () => {
  //获取轮播图地址
  let attaImageList: any = [];
  fileList.value.forEach((item) => {
    attaImageList.push(item.response.data);
  });
  formAtta.value.attaImages = JSON.stringify(attaImageList);
  //获取视频地址
  if (videoList.value.length <= 0) {
    ElMessage.error("请上传视频");
    return;
  }
  formAtta.value.attaVideo = videoList.value[0].response.data;

  addProdAtta(formAtta.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisibless.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//商品明细
const handleProdInfo = (row: any) => {
  console.log(row);
  router.push("/home/prodInfo/" + row.prodId);
};

onMounted(() => {
  loadList();

  //获取商品标签下拉框
  getTag().then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });

  //获取商品单位下拉框
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });

  //获取商品类型下拉框
  getSelectTypeTree().then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });

  //获取商品品牌下拉框
  getBrandList({
    pageNum: 1,
    pageSize: 9999,
  }).then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data.records;
    }
  });
});
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
